package com.xzlf.config;

import com.xzlf.domain.JobTask;
import com.xzlf.service.impl.JobTaskService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Configuration
@EnableScheduling
@Slf4j
public class ScheduledConfig02 implements SchedulingConfigurer {

    private static final SimpleDateFormat SIMPLE_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    private static JobTask jobTask;
    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private JobTaskService jobTaskService;

    @Value("${task.lock.key1}")
    private String lockKey1;

    @Value("${task.lock.key2}")
    private String lockKey2;

    @Value("${task.lock.key3}")
    private String lockKey3;

    @Value("${task.lock.value1}")
    private String lockValue1;

    @Value("${task.lock.value2}")
    private String lockValue2;

    @Value("${server.name}")
    private String serverName;

    @Value("${job.execute.enable}")
    private boolean isExecute;

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        jobTask = jobTaskService.getById(1);
        taskRegistrar.addCronTask(
                () -> {
                    RLock rlock = redissonClient.getLock(lockKey1);
                    try {
                        boolean lock = rlock.tryLock(2, -1, TimeUnit.SECONDS);
                        if (!lock) {
                            return;
                        }
                        log.info("{}--{}", serverName, SIMPLE_DATE_FORMAT.format(new Date()));
                        TimeUnit.SECONDS.sleep(10);
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        if (rlock.isLocked()) {// 是否还是锁定状态
                            if (rlock.isHeldByCurrentThread()) {// 是否是当前执行线程的锁
                                log.info("我是：{}，完成了:{}，开始释放锁。", serverName, jobTask.getJobDesc());
                                rlock.unlock();
                            }
                        } else {
                            log.info("我是：{}，没有抢到锁，无需释放。", serverName);
                        }
                    }
                }, jobTask.getJobCron());
    }
}
